﻿Command = {
    runOn: function(target, commandName) {
        var args = new Array();
        for (var i = 1; i < arguments.length; i++)
            args[i - 1] = arguments[i];
        return Command.run.call(target, commandName, args);
    },
    run: function(commandName, args) {
        if (args == undefined)
            args = new Array();
        if (arguments.length > 2) {
            var firstValue = args;
            args = new Array();
            args[0] = firstValue;
            for (var i = 2; i < arguments.length; i++)
                args[i - 1] = arguments[i];
        }
        if (args instanceof Array)
            return Command._registeredCommands[commandName].apply(this, args);
        return Command._registeredCommands[commandName].call(this, args);
    },
    register: function(commandName, code, exclusive) {
        if (typeof (commandName) == 'string') {
            var commandAction = code;
            if (typeof (code) == 'string') {
                commandAction = function() {
                    eval(code);
                }
            }
            else if (typeof (code) == 'object') {
                //Deal with namespaced commands
                for (var propName in code) {
                    if (!Command._registeredCommands)
                        Command._registeredCommands = {};
                    Command._registeredCommands[commandName] = code;
                    var func = Command.register(commandName + '.' + propName, code[propName]);
                    if (typeof (func) == 'function') {
                        Command.register(propName, code[propName])
                    }
                }
                return;
            }
            else
                commandAction = code;
            if (!exclusive && Command._registeredCommands && Command._registeredCommands[commandName]) {
                return Command._registeredCommands[commandName] = Command._combine(Command._registeredCommands[commandName], commandAction);
            }
            else {
                if (!Command._registeredCommands)
                    Command._registeredCommands = {};
                return Command._registeredCommands[commandName] = commandAction;
            }
        }
        else if (typeof (commandName == 'object')) {
            for (var propName in commandName) {
                Command.register(propName, commandName[propName]);
            }
        }
    },
    _combine: function(baseFunc, handler) {
        return function() {
            var args = {};
            for (var i = 0; i < arguments.length; i++)
                args[i] = arguments[i];
            if (baseFunc.call(this, args) !== false)
                return handler.call(this, args)
        }
    }
}